Scroll Progress Bar

Do While Loop

In C++, a do-while loop is a control structure that is similar to the while loop. The primary difference is that in a do-while loop, the condition is evaluated after the loop body is executed. This ensures that the loop body is executed at least once, even if the condition is initially false. Here's the basic syntax of a do-while loop:

Program:

do {
    // Code to be executed
} while (condition);

condition: A Boolean expression that is evaluated after each execution of the loop body. If the condition is true, the loop continues; if it's false, the loop terminates.

Here's an example of a do-while loop that asks the user to enter a positive number and continues to do so until a negative number is entered:

Program:

#include <iostream>

int main() {
    int num;

    do {
        std::cout << "Enter a positive number (enter a negative number to stop): ";
        std::cin >> num;

        if (num >= 0) {
            std::cout << "entered: " << num << std::endl;
        }
    } while (num >= 0);

    std::cout << "Loop finished." << std::endl;

    return 0;
}

In this example, the loop body prompts the user for input and displays the entered number. The loop continues to execute until the user enters a negative number, at which point the loop terminates.

Key points about do-while loops:
  • The loop body is guaranteed to execute at least once because the condition is evaluated after the first execution of the loop body.
  • After each iteration, the loop checks the condition. If the condition is false, the loop terminates; otherwise, it continues to execute.
  • Be cautious when using do-while loops to ensure that the condition eventually becomes false to prevent infinite loops.
  • it can use any valid Boolean expression as the loop condition.
  • it can have multiple statements inside the loop block enclosed within curly braces {}.
  • do-while loops are particularly useful when need to execute a block of code at least once, such as menu-driven programs or input validation, where want to ensure that a specific action is performed before checking the condition.

question


answer

question2


answer2